package com.logica.mdm.webservices.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.logica.mdm.webservices.dao.SearchPartyElectronicAddressDao;
import com.logica.mdm.webservices.dao.beans.PartyElectronicAddressResultBean;

/**
 * Implementation using NamedParameterJdbcTemplate
 */
@Repository
public class JdbcSearchPartyElectronicAddressDaoImpl implements SearchPartyElectronicAddressDao {

	private NamedParameterJdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
	    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<PartyElectronicAddressResultBean> searchPartyElectronicAddress(String sqlQuery, Map<String, ?> sqlParams) {
		return this.jdbcTemplate.query(sqlQuery, sqlParams, new PartyElectronicAddressMapper());
	}

	/**
	 * Inner class defining the mapping between the database and PartyElectronicAddressResultBean
	 */
	private static final class PartyElectronicAddressMapper implements RowMapper<PartyElectronicAddressResultBean> {
		public PartyElectronicAddressResultBean mapRow(ResultSet rs, int rowNum) throws SQLException {
			PartyElectronicAddressResultBean electronicAddress = new PartyElectronicAddressResultBean();
			electronicAddress.setElectronicAddress(rs.getString("ELECTRONIC_ADDRESS"));
			electronicAddress.setElectronicAddressType(rs.getString("ELECTRONIC_ADDRESS_TYPE"));
			electronicAddress.setMdmId(rs.getString("PARTY_ID"));
	        return electronicAddress;
	    }
	}
}
